<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>背单词小游戏</title>
    <style>
        body {
            font-family: 'Comic Sans MS', -apple-system, BlinkMacSystemFont, "SF Pro Text", "SF Pro Icons", "Helvetica Neue", Arial, sans-serif;
           
            margin: 0 auto;
            padding: 10px;
            text-align: center;
            background-color: #f0f6ff;
            color: #1d1d1f;
            background-image: linear-gradient(120deg, #e0f0ff 0%, #fff8f0 100%);
            max-width: 100%;
            overflow-x: hidden;
        }

        #word-container {
            width: calc(100% - 20px);
            height: 50vh;
            min-height: 300px;
            margin: 10px auto;
            position: relative;
            overflow: hidden;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 15px;
            box-shadow: 0 4px 16px rgba(0, 123, 255, 0.15);
            border: 2px solid #4a90e2;
        }

        .word-bullet {
            position: absolute;
            font-size: 20px;
            color: #1d1d1f;
            cursor: pointer;
            padding: 8px 16px;
            border-radius: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            animation: float 3s ease-in-out infinite;
            background: linear-gradient(45deg, var(--gradient-start), var(--gradient-end));
            border: 1px solid var(--border-color);
            -webkit-tap-highlight-color: transparent;
        }

        #word-input {
            width: calc(100% - 32px);
            max-width: none;
            height: 100px;
            margin: 15px auto;
            padding: 12px;
            font-size: 16px;
            line-height: 1.4;
            border-radius: 12px;
            border: 2px solid #4a90e2;
            box-sizing: border-box;
        }

        #player-input {
            width: calc(100% - 32px);
            max-width: none;
            min-height: 48px;
            padding: 5px;
            font-size: 18px;
            border-radius: 12px;
            margin: 10px auto;
            box-sizing: border-box;
        }

        #letter-container {
            width: calc(100% - 32px);
            margin: 10px auto;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 5px;
        }

        .letter {
            font-size: 18px;
            padding: 8px 12px;
            margin: 4px;
            -webkit-tap-highlight-color: transparent;
        }

        #start-btn, #clear-btn {
            font-size: 20px;
            padding: 12px 30px;
            margin: 10px;
            border-radius: 25px;
            -webkit-tap-highlight-color: transparent;
        }

        #score {
            font-size: 16px;
            
        }

        @media (max-width: 480px) {
            .word-bullet {
                font-size: 18px;
                padding: 6px 12px;
            }
            
            #start-btn, #clear-btn {
                font-size: 18px;
                padding: 10px 24px;
            }
            
            .letter {
                font-size: 16px;
                padding: 6px 10px;
            }
        }

        @keyframes float {
            0% {
                transform: translateY(0px);
            }

            50% {
                transform: translateY(-10px);
            }

            100% {
                transform: translateY(0px);
            }
        }

        .word-bullet:hover {
            transform: scale(1.1) rotate(2deg);
            background-color: #4a90e2;
            color: white;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
        }

        #word-input {
            width: 100%;
            max-width: 600px;
            height: 150px;
            margin: 30px auto;
            padding: 16px;
            font-size: 17px;
            line-height: 1.5;
            border-radius: 20px;
            border: 3px solid #4a90e2;
            background-color: rgba(255, 255, 255, 0.9);
            transition: all 0.3s ease;
            resize: none;
            font-family: inherit;
        }

        #word-input:focus {
            outline: none;
            border-color: #ff6b6b;
            box-shadow: 0 0 0 4px rgba(255, 107, 107, 0.1);
            transform: scale(1.02);
        }

        #player-input {
            width: 100%;
            max-width: 400px;
            height: 48px;
            
            font-size: 20px;
            border-radius: 20px;
            border: 3px solid #4a90e2;
            margin-bottom: 20px;
            background-color: rgba(255, 255, 255, 0.9);
            transition: all 0.3s ease;
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            overflow-y: auto;
            margin: 0 auto;

        }

        .selected-letter {
            padding: 10px;
            background-color: #4a90e2;
            color: white;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .selected-letter:hover {
            background-color: #ff6b6b;
            transform: scale(1.1);
        }

        #clear-btn {
            font-size: 24px;
            font-weight: 600;
            padding: 15px 40px;
            margin: 20px;
            background-color: #ff6b6b;
            color: white;
            border: none;
            border-radius: 30px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 6px 0 #e64c4c;
            position: relative;
            top: 0;
            display: inline-block;
            /* 修改为 inline-block 以便与输入框同行 */
            vertical-align: middle;
            /* 垂直居中对齐 */
        }

        #clear-btn:hover {
            background-color: #ff8787;
            transform: translateY(-2px);
            box-shadow: 0 8px 0 #e64c4c;
        }

        #clear-btn:active {
            top: 6px;
            box-shadow: 0 0 0 #e64c4c;
        }

        #start-btn {
            font-size: 24px;
            font-weight: 600;
            padding: 15px 40px;
            margin: 20px;
            background-color: #ff6b6b;
            color: white;
            border: none;
            border-radius: 30px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 6px 0 #e64c4c;
            position: relative;
            top: 0;
        }

        #start-btn:hover {
            background-color: #ff8787;
            transform: translateY(-2px);
            box-shadow: 0 8px 0 #e64c4c;
        }

        #start-btn:active {
            top: 6px;
            box-shadow: 0 0 0 #e64c4c;
        }

        #score {
            font-size: 18px;
            font-weight: 700;
            color: #4a90e2;
            text-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
            animation: pulse 2s ease-in-out infinite;
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.05);
            }

            100% {
                transform: scale(1);
            }
        }

        .letter {
            display: inline-block;
            margin: 5px;
            padding: 10px 15px;
            font-size: 20px;
            background-color: #4a90e2;
            color: white;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .letter:hover {
            background-color: #ff6b6b;
            transform: scale(1.1);
        }
    </style>
</head>

<body>
    <!-- 修改这部分 -->
    <div style="display: flex; justify-content: center; align-items: center; gap: 20px; margin: 10px 0;">
        <div id="score">得分: 0</div>
        <div style="display: flex; align-items: center;">
            <label for="speed-select" style="margin-right: 10px;">难度：</label>
            <select id="speed-select" style="padding: 8px; border-radius: 8px; border: 2px solid #4a90e2;">
                <option value="0.2">简单</option>
                <option value="0.5">中等</option>
                <option value="1.0">困难</option>
                <option value="2.0">专家</option>
            </select>
        </div>
    </div>
    <div id="word-container"></div>
    <div style="display: flex; align-items: center;">
        <div id="player-input"></div>
         <!-- 新增清空按钮 -->
    </div>
    <div id="letter-container"></div> <!-- 新增字母容器 -->
    <div style="display: flex; align-items: center;">
        <button id="start-btn">开始游戏</button>
        <button id="clear-btn">清空</button>
    </div>
    
    <br>
    <textarea id="word-input" placeholder="请输入单词，每行一个">hello
world
apple
banana</textarea>

    <script>
        const wordContainer = document.getElementById('word-container');
        const startBtn = document.getElementById('start-btn');
        const wordInput = document.getElementById('word-input');
        const playerInput = document.getElementById('player-input');
        const scoreDisplay = document.getElementById('score');
        let words = [];
        let gameInterval;
        let score = 0;
        let wordCounts = {};
        let audioCache = new Map(); // 用于存储预加载的音频

        // 游戏配置项
        const gameConfig = {
            // 单词下落速度 (像素/帧)
            // 值越小，下落越慢。建议范围：0.2-2.0
            // 0.2: 非常慢
            // 0.5: 较慢
            // 1.0: 中等
            // 2.0: 较快
            fallSpeed: 0.2,
            
            // 单词生成间隔 (毫秒)
            // 值越大，生成间隔越长。建议范围：2000-5000
            spawnInterval: 4000
        };

        // 添加速度选择事件监听
        document.getElementById('speed-select').addEventListener('change', function(e) {
            gameConfig.fallSpeed = parseFloat(e.target.value);
            // 根据速度调整生成间隔
            gameConfig.spawnInterval = 5000 - (gameConfig.fallSpeed * 1000);
            
            // 如果游戏正在进行，重新开始以应用新速度
            if (gameInterval) {
                clearInterval(gameInterval);
                gameInterval = setInterval(createWordBullet, gameConfig.spawnInterval);
            }
        });

        function initWords () {
            words = wordInput.value.split('\n').filter(word => word.trim() !== '');
            wordCounts = {};
            words.forEach(word => {
                wordCounts[word] = 0;
            });
        }

        function getRandomColor () {
            const hue = Math.floor(Math.random() * 360);
            return `hsl(${hue}, 80%, 80%)`;
        }

        function createWordBullet () {
            const availableWords = words.filter(word => wordCounts[word] < 3);
            if (availableWords.length === 0) {
                clearInterval(gameInterval);
                const congratsMsg = document.createElement('div');
                congratsMsg.style.position = 'absolute';
                congratsMsg.style.top = '50%';
                congratsMsg.style.left = '50%';
                congratsMsg.style.transform = 'translate(-50%, -50%)';
                congratsMsg.style.fontSize = '32px';
                congratsMsg.style.fontWeight = 'bold';
                congratsMsg.style.color = '#0071e3';
                congratsMsg.style.padding = '20px';
                congratsMsg.style.background = 'rgba(255, 255, 255, 0.95)';
                congratsMsg.style.borderRadius = '16px';
                congratsMsg.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.1)';
                congratsMsg.style.animation = 'fadeIn 0.5s ease-out';
                congratsMsg.textContent = '恭喜你完成所有单词！';
                wordContainer.innerHTML = '';
                wordContainer.appendChild(congratsMsg);

                // 创建彩带特效
                for (let i = 0; i < 50; i++) {
                    const confetti = document.createElement('div');
                    confetti.style.position = 'absolute';
                    confetti.style.width = Math.random() * 10 + 5 + 'px';
                    confetti.style.height = Math.random() * 20 + 10 + 'px';
                    confetti.style.backgroundColor = `hsl(${Math.random() * 360}, 100%, 50%)`;
                    confetti.style.left = Math.random() * 100 + '%';
                    confetti.style.top = '-20px';
                    confetti.style.opacity = '0.8';
                    confetti.style.transform = `rotate(${Math.random() * 360}deg)`;
                    confetti.style.borderRadius = '4px';
                    wordContainer.appendChild(confetti);

                    const fallDuration = Math.random() * 2 + 2;
                    const swayDuration = Math.random() * 2 + 2;
                    confetti.style.animation = `
                        fall ${fallDuration}s linear forwards,
                        sway ${swayDuration}s ease-in-out infinite alternate
                    `;
                }

                // 添加动画关键帧
                if (!document.querySelector('#confetti-animations')) {
                    const style = document.createElement('style');
                    style.id = 'confetti-animations';
                    style.textContent = `
                        @keyframes fall {
                            to {
                                top: 120%;
                                transform: rotate(${Math.random() * 720 + 360}deg);
                            }
                        }
                        @keyframes sway {
                            from {
                                transform: translateX(-20px) rotate(-45deg);
                            }
                            to {
                                transform: translateX(20px) rotate(45deg);
                            }
                        }
                    `;
                    document.head.appendChild(style);
                }
                return;
            }
            const word = availableWords[Math.floor(Math.random() * availableWords.length)];
            const bullet = document.createElement('div');
            bullet.className = 'word-bullet';
            bullet.textContent = word;
            bullet.style.left = Math.random() * (wordContainer.offsetWidth - 100) + 'px';
            bullet.style.top = '-50px';
            const color1 = getRandomColor();
            const color2 = getRandomColor();
            bullet.style.setProperty('--gradient-start', color1);
            bullet.style.setProperty('--gradient-end', color2);
            bullet.style.setProperty('--border-color', color2);
            wordContainer.appendChild(bullet);

            let posY = -50;
            // 使用配置的下落速度
            const speed = gameConfig.fallSpeed + Math.random() * 0.2;

            function animate () {
                posY += speed;
                bullet.style.top = posY + 'px';

                if (posY < wordContainer.offsetHeight) {
                    requestAnimationFrame(animate);
                } else {
                    bullet.remove();
                }
            }

            animate();

            bullet.addEventListener('click', () => {
                playWordAudio(word);
            });

            // 初始化letter-container
            if (wordContainer.childElementCount === 1) {
                generateRandomLetters();
            }
        }

        function generateRandomLetters () {
            const visibleBullets = document.querySelectorAll('.word-bullet');
            const lettersSet = new Set();
            visibleBullets.forEach(bullet => {
                bullet.textContent.toLowerCase().split('').forEach(letter => {
                    lettersSet.add(letter);
                });
            });
            const letters = Array.from(lettersSet);
            // 增加生成的字母数量
            while (letters.length < 8) {
                const randomLetter = String.fromCharCode(97 + Math.floor(Math.random() * 26));
                letters.push(randomLetter);
            }
            // 随机在前后增加字母
            const additionalLetters = [];
            for (let i = 0; i < 2; i++) {
                const randomLetter = String.fromCharCode(97 + Math.floor(Math.random() * 26));
                additionalLetters.push(randomLetter);
            }
            letters.unshift(...additionalLetters);
            letters.push(...additionalLetters);
            const letterContainer = document.getElementById('letter-container');
            letterContainer.innerHTML = ''; // 清空旧的字母
            letters.forEach(letter => {
                const letterElement = document.createElement('div');
                letterElement.className = 'letter';
                letterElement.textContent = letter;
                letterElement.addEventListener('click', () => {
                    addSelectedLetter(letter);
                });
                letterContainer.appendChild(letterElement);
            });
        }

        function addSelectedLetter (letter) {
            const letterElement = document.createElement('div');
            letterElement.className = 'selected-letter';
            letterElement.textContent = letter;
            letterElement.addEventListener('click', () => {
                letterElement.remove();
                updatePlayerInput();
                checkPlayerInput(); // 新增：检测是否可以消除一个单词
            });
            playerInput.appendChild(letterElement);
            updatePlayerInput();
            checkPlayerInput(); // 新增：检测是否可以消除一个单词
        }

        function updatePlayerInput () {
            const letters = Array.from(playerInput.children).map(child => child.textContent).join('');
            playerInput.dataset.value = letters;
        }

        function checkPlayerInput () {
            const input = playerInput.dataset.value.trim();
            if (checkWord(input)) {
                playerInput.innerHTML = ''; // 清空已选择的字母
                playerInput.dataset.value = '';
            }
        }

        function checkWord (input) {
            const bullets = document.querySelectorAll('.word-bullet');
            for (const bullet of bullets) {
                if (bullet.textContent.toLowerCase() === input.toLowerCase()) {
                    bullet.remove();
                    score += 10;
                    wordCounts[input.toLowerCase()]++;
                    scoreDisplay.textContent = `得分: ${score} (${input}: ${wordCounts[input.toLowerCase()]}/3)`;
                    playWordAudio(input);
                    generateRandomLetters(); // 成功消除单词后重新生成随机字母
                    playerInput.innerHTML = ''; // 清空已选择的字母
                    playerInput.dataset.value = '';
                    return true;
                }
            }
            return false;
        }

        function playWordAudio(word) {
            const audio = audioCache.get(word);
            if (audio) {
                // 重置音频并播放
                audio.currentTime = 0;
                audio.play().catch(error => {
                    console.error('Error playing audio:', error);
                });
            } else {
                console.warn(`Audio not found in cache for word: ${word}`);
            }
        }

        async function preloadWordAudio(word) {
            try {
                const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
                const data = await response.json();

                if (data && data[0] && data[0].phonetics && data[0].phonetics.length > 0) {
                    const audioUrl = data[0].phonetics.find(p => p.audio)?.audio;
                    if (audioUrl) {
                        const audio = new Audio(audioUrl);
                        audioCache.set(word, audio);
                        return true;
                    }
                }
                return false;
            } catch (error) {
                console.error(`Error preloading audio for ${word}:`, error);
                return false;
            }
        }

        async function startGame() {
            initWords();
            score = 0;
            scoreDisplay.textContent = `得分: ${score}`;
            wordContainer.innerHTML = '';
            playerInput.innerHTML = '';
            playerInput.dataset.value = '';
            playerInput.focus();
            document.getElementById('letter-container').innerHTML = '';

            if (gameInterval) {
                clearInterval(gameInterval);
            }

            // 预加载所有单词的语音
            const loadingMsg = document.createElement('div');
            loadingMsg.style.position = 'absolute';
            loadingMsg.style.top = '50%';
            loadingMsg.style.left = '50%';
            loadingMsg.style.transform = 'translate(-50%, -50%)';
            loadingMsg.style.fontSize = '24px';
            loadingMsg.style.color = '#4a90e2';
            loadingMsg.textContent = '正在加载语音资源...';
            wordContainer.appendChild(loadingMsg);

            // 清空现有的音频缓存
            audioCache.clear();

            // 并行预加载所有单词的语音
            const preloadPromises = words.map(word => preloadWordAudio(word));
            await Promise.all(preloadPromises);

            // 移除加载提示
            loadingMsg.remove();

            gameInterval = setInterval(createWordBullet, 3000);
            generateRandomLetters();
        }

        startBtn.addEventListener('click', startGame);

        // 新增清空按钮点击事件监听器
        document.getElementById('clear-btn').addEventListener('click', () => {
            playerInput.innerHTML = ''; // 清空已选择的字母
            playerInput.dataset.value = '';
            generateRandomLetters(); // 重新生成随机字母
        });

        // 新增 input 事件监听器
        playerInput.addEventListener('input', () => {
            const input = playerInput.dataset.value.trim();
            if (checkWord(input)) {
                playerInput.innerHTML = ''; // 清空已选择的字母
                playerInput.dataset.value = '';
            }
        });
    </script>
</body>

</html>